const schedule = require('node-schedule');
const fs = require('fs')
const exec = require('child_process').exec;
// const spider = require('./spider')
const requestXML = require('./createXML').requestXML
const path = require('path')
const env = require('../config/env')

let hasSiteMap = false
let sitemapPath = path.resolve(__dirname, '../zl_news_sitemap')
try{
  let sitemapPathInfo = fs.statSync(sitemapPath)
  // 判断是否为文件
  hasSiteMap = sitemapPathInfo.isDirectory() ? true : false

}catch(err){}


// requestXML()

if (!hasSiteMap) {//zl_news_sitemap不存在则拉取文件
  let initialRand = Math.floor(Math.random() * 30 + 1)  * 1000
  console.log('Time:'+parseInt(Date.now()/1000),'sitemap dir is not exist, init:'+sitemapPath)
  setTimeout(function() {
    try {
      exec(`bash ${path.resolve(__dirname, '../hooks/auto-pull-xml.sh')}`, err => {
        console.log('Time:'+parseInt(Date.now()/1000),'initial zl_news_sitemap:' + (err?'success':'failed'))
      })
    } catch (error) {
      console.log('Time:'+parseInt(Date.now()/1000),'initial zl_news_sitemap exception',error)
    }

  },initialRand)
}

let isCp = false
if(env.environment === 'isProd'){
  try{
    const info = fs.statSync('/home/nginx/admin')
    // 判断是否为文件
    isCp = info.isDirectory() ? true : false
  }catch(err){}
}
// requestXML()
function startSchedule() {
  //只有生产环境才运行
  if (env.environment !== 'isProd') return

  let minRand = Math.floor(Math.random() * 50 + 1)
  if(isCp) {
    let pushSchedule = '0 ' + minRand + ' 2 * * *'
    schedule.scheduleJob(pushSchedule,()=>{
      console.log('Time:'+parseInt(Date.now()/1000),'pushSchedule begin')
      try {
        exec(`bash ${path.resolve(__dirname, '../hooks/auto-push-xml.sh')}`, err => {
          console.log('Time:'+parseInt(Date.now()/1000),'pushSchedule begin requestXML',err)
          requestXML()
        })
      } catch (error) {
        console.log('Time:'+parseInt(Date.now()/1000),'pushSchedule exec falied',error)
      }

    }); 
  } else {  //非cp环境下定时拉取sitemapxml
    let pullSchedule = '0 ' + minRand + ' 4 * * *'
    schedule.scheduleJob(pullSchedule,()=>{
      console.log('Time:'+parseInt(Date.now()/1000),'pullSchedule begin')
      try {
        exec(`bash ${path.resolve(__dirname, '../hooks/auto-pull-xml.sh')}`, err => {
          console.log('Time:'+parseInt(Date.now()/1000),'pullSchedule end',err)
        })
      } catch (error) {
        console.log('Time:'+parseInt(Date.now()/1000),'pullSchedule exec falied',error)
      }

    }); 
  }
}

function startPull(callback) {//提供接口推git
  if (env.environment !== 'isProd') {
    callback && callback({code:1,msg:'current env is not prod'})
    return
  }

  try {
    exec(`bash ${path.resolve(__dirname, '../hooks/auto-pull-xml.sh')}`, err => {
      console.log('Time:'+parseInt(Date.now()/1000),'pullSchedule end',err)
      callback && callback({code:err?1:0,msg:err?JSON.stringify(err):'success'})
    })
  } catch (error) {
    callback && callback({code:error?1:0,msg:error?JSON.stringify(error):'success'})
    console.log('Time:'+parseInt(Date.now()/1000),'pullSchedule exec falied',error)
  }

}

function startPush(callback) {//提供接口拉git
  if (env.environment !== 'isProd') {
    callback && callback({code:1,msg:'current env is not prod'})
    return
  }
  if (!isCp) {
    callback && callback({code:1,msg:'current env is not cp'})
    return
  }
  console.log('Time:'+parseInt(Date.now()/1000),'pushSchedule begin requestXML')
  requestXML(callback)
}


let scheduleCronstyle = {}
scheduleCronstyle.startSchedule = startSchedule
scheduleCronstyle.startPull = startPull
scheduleCronstyle.startPush = startPush

module.exports = scheduleCronstyle
